//
//  SendWeiboViewController.m
//  Project_2_weibo
//
//  Created by 林林 on 16/6/25.
//  Copyright © 2016年 lhn. All rights reserved.
//

#import "SendWeiboViewController.h"
#import "LocationViewController.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "SinaWeibo+sendWeibo.h"
#import "EmotionInputView.h"

#define kToolViewHeight (40 + 20)
#define kLocationViewHeight 20

@interface SendWeiboViewController () <SinaWeiboRequestDelegate>
{
    UITextView *_inputTextView;
    UIView *_toolView;
    //location
    UIImageView *_locationIcon;
    ThemeLabel *_locationTitle;
    ThemeButton *_locationCancelButton;
    //表情输入界面
    EmotionInputView *_emotionInputView;
}

@property (nonatomic, copy) NSDictionary *locationDic;

@end

@implementation SendWeiboViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"发布微博";
    [self createNavBarButton];
    [self createInputTextView];
    [self createToolView];
    [self createLocationViews];
    
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidClose:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)createNavBarButton {
    
    //取消
    ThemeButton *backButton = [ThemeButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 60, 44);
    backButton.backgroundImageName = @"titlebar_button_9.png";
    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backItem;
    
    //发送
    ThemeButton *sendButton = [ThemeButton buttonWithType:UIButtonTypeCustom];
    sendButton.frame = CGRectMake(0, 0, 60, 44);
    sendButton.backgroundImageName = @"titlebar_button_9.png";
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *sendItem = [[UIBarButtonItem alloc] initWithCustomView:sendButton];
    self.navigationItem.rightBarButtonItem = sendItem;
}

#pragma mark - subViews
- (void)createInputTextView {
    
    _inputTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - kToolViewHeight)];
    _inputTextView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_inputTextView];
}

- (void)createToolView {
    
    _toolView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kToolViewHeight)];
    _toolView.top = _inputTextView.bottom;
    [self.view addSubview:_toolView];
    
    //创建五个按钮
    NSArray *imageNames = @[@"compose_toolbar_1.png",
                            @"compose_toolbar_3.png",
                            @"compose_toolbar_4.png",
                            @"compose_toolbar_5.png",
                            @"compose_toolbar_6.png",
                            ];
    CGFloat buttonWidth = kScreenWidth / imageNames.count;
    for (int i = 0; i < imageNames.count; i++) {
        ThemeButton *button = [ThemeButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(buttonWidth * i, kLocationViewHeight, buttonWidth, kToolViewHeight - kLocationViewHeight);
        button.imageName = imageNames[i];
        [_toolView addSubview:button];
        
        button.tag = i;
        [button addTarget:self action:@selector(toolButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
}

#pragma mark - button action
- (void)backAction:(UIButton *)button {
    
    [_inputTextView resignFirstResponder];
    //返回
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendAction:(UIButton *)button {
    
    NSString *text = [_inputTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (text.length ==  0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发送失败" message:@"微博正文不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    
    //显示HUD
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithWindow:self.view.window];
    [self.view.window addSubview:hud];
    //显示文本信息
    hud.labelText = @"正在发送";
    //设置背景变暗
    hud.dimBackground = YES;
    //显示HUD
    [hud show:YES];
    
    SinaWeibo *weibo = kWeiboObject;
    NSMutableDictionary *paramas = [@{@"status" : text} mutableCopy];
//    [weibo requestWithURL:@"statuses/update.json" params:paramas httpMethod:@"POST" delegate:self];

    [weibo sendText:text
              image:nil
             params:paramas
             sucess:^(id result) {
                 NSLog(@"发送成功");
                 [self backAction:nil];
                 
                 //隐藏HUD
                 hud.labelText = @"发送成功";
                 [hud hide:YES afterDelay:2];
             }
               fail:^(NSError *error) {
                   NSLog(@"发送失败");
                   [self backAction:nil];
                   
                   //隐藏HUD
                   hud.labelText = @"发送失败";
                   [hud hide:YES afterDelay:2];
               }];
}

- (void)toolButtonAction:(UIButton *)button {
    
    if (button.tag == 3) {
        //打开定位
        LocationViewController *lVC = [[LocationViewController alloc] init];
        //回传block
        lVC.block = ^(NSDictionary *locationResult){
            self.locationDic = locationResult;
        };

        [self.navigationController pushViewController:lVC animated:YES];
    } else if (button.tag == 4) {
        if (_emotionInputView == nil) {
            _emotionInputView = [[EmotionInputView alloc] init];
        }
        _inputTextView.inputView = _inputTextView.inputView ? nil : _emotionInputView;
        //重新加载输入视图
        [_inputTextView reloadInputViews];
        //强制显示输入视图
        [_inputTextView  becomeFirstResponder];
    }
}

#pragma mark - 键盘
- (void)keyboardDidShow:(NSNotification *)notification {
    
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _toolView.bottom = kScreenHeight - 64 - keyboardFrame.size.height;
    _inputTextView.height = kScreenHeight - 64 - keyboardFrame.size.height - kToolViewHeight;
}

- (void)keyboardDidClose:(NSNotification *)notification {
    
    _toolView.bottom = kScreenHeight - 64;
    _inputTextView.height = kScreenHeight - 64 - kToolViewHeight;
    
}
#pragma mark - SinaWeiboRequestDelegate
- (void)request:(SinaWeiboRequest *)request didReceiveResponse:(NSURLResponse *)response {
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSLog(@"收到响应，状态码：%li", httpResponse.statusCode);
    [self backAction:nil];
}

#pragma mark - create locationView
- (void)createLocationViews {
    
    _locationIcon = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, kLocationViewHeight, kLocationViewHeight)];
    //    _locationIcon.backgroundColor = [UIColor redColor];
    [_toolView addSubview:_locationIcon];
    
    _locationTitle = [[ThemeLabel alloc] initWithFrame:CGRectMake(15 + kLocationViewHeight, 0, 100, kLocationViewHeight)];
    _locationTitle.colorName = @"More_Item_Text_color";
//    _locationTitle.text = @"More_Item_Text_color";
    //    _locationTitle.backgroundColor = [UIColor orangeColor];
    [_toolView addSubview:_locationTitle];
    
    
    _locationCancelButton = [ThemeButton buttonWithType:UIButtonTypeCustom];
    _locationCancelButton.frame = CGRectMake(0, 0, kLocationViewHeight, kLocationViewHeight);
    _locationCancelButton.left = _locationTitle.right + 5;
    _locationCancelButton.imageName = @"compose_toolbar_clear.png";
    
    [_locationCancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [_toolView addSubview:_locationCancelButton];
    
    
}

#pragma mark - 改变定位界面显示内容
- (void)setLocationDic:(NSDictionary *)locationDic {
    
    if (locationDic == _locationDic) {
        return;
    }
    
    _locationDic = locationDic;
    //1 传入了一个新的位置信息
    //更新界面显示的内容
    if (_locationDic) {
        //显示定位信息界面
        _locationCancelButton.hidden = NO;
        _locationTitle.hidden = NO;
        _locationIcon.hidden = NO;
        //加载内容
        _locationTitle.text = _locationDic[@"title"];
        [_locationIcon sd_setImageWithURL:[NSURL URLWithString:_locationDic[@"icon"]]];
        
        //计算字体宽度
        CGRect rect = [_locationTitle.text boundingRectWithSize:CGSizeMake(kScreenWidth - 40 - 40, kLocationViewHeight) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : _locationTitle.font} context:nil];
        CGFloat labelWidth = rect.size.width;
        _locationTitle.width = labelWidth;
        _locationCancelButton.left = _locationTitle.right + 5;
        
    } else {
        //2 传入了一个空的位置信息
        //隐藏定位信息界面
        _locationCancelButton.hidden = YES;
        _locationTitle.hidden = YES;
        _locationIcon.hidden = YES;
    }
}


#pragma mark - cancelAction
- (void)cancelAction {
    self.locationDic = nil;
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
